package com.app.fenak.asynctasks;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.app.fenak.EmailActivity;
import com.app.fenak.LoginActivity;
import com.app.fenak.RegisterActivity;
import com.app.fenak.validation.ServicesUrls;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class CheckEmailAsyncTask extends AsyncTask<Object, Object, Boolean> {

	private EmailActivity emailActivity;
	private Intent intent;

	@Override
	protected Boolean doInBackground(Object... args) {

		emailActivity = (EmailActivity) args[0];
		String email = (String) args[1];
		boolean emailExist = false;

		try {

			ArrayList<NameValuePair> requestString = new ArrayList<NameValuePair>();
			requestString.add(new BasicNameValuePair(
					ServicesUrls.CHECK_EMAIL_PARAM_EMAIL, email));

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(ServicesUrls.CHECK_EMAIL_URL);
			httpPost.setEntity(new UrlEncodedFormEntity(requestString));
			Log.i("request ", httpPost.getRequestLine().toString());

			HttpResponse response = httpClient.execute(httpPost);
			Log.i("response", response.getStatusLine().toString());
			String resonseString = ServicesUrls.convertStreamToString(response
					.getEntity().getContent());
			Log.i("response ", resonseString);
			JSONObject jsonObject = new JSONObject(resonseString);
			emailExist = jsonObject.getBoolean("post");
			Log.i(" email exists", emailExist + "");

		} catch (UnsupportedEncodingException e) {

			Log.e("UnsupportedEncodingException", e.getMessage());
		} catch (IOException e) {

			Log.e("IOException", e.getMessage());

		} catch (JSONException e) {

			Log.e("JSONException", e.getMessage());
		}

		return emailExist;
	}

	@Override
	protected void onPostExecute(Boolean result) {

		super.onPostExecute(result);

		if (!result) {
			intent = new Intent(emailActivity.getApplicationContext(),
					LoginActivity.class);
			emailActivity.startActivity(intent);
		} else {
			intent = new Intent(emailActivity.getApplicationContext(),
					RegisterActivity.class);
			emailActivity.startActivity(intent);
		}

		emailActivity.finish();
		emailActivity.dismissProgressDialog();
	}

}
